package com.soft.bams.dao;

import com.soft.bams.entity.Account;

import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author yzg
 * @desc TODO
 * @date 2025/4/23
 */
public class FileDao implements IDao<Account, List<Account>>{
    private Long currentId;
    private List<Account> accounts;

    public FileDao() {
        this.accounts = loadAccounts();
        this.currentId = loadCurrentId();
    }

    // 加载当前ID
    private Long loadCurrentId() {
        File file = new File("id.txt");
        if (!file.exists()) {
            return initializeFirstId();
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String idStr = reader.readLine();
            if (idStr != null && !idStr.isEmpty()) {
                return Long.parseLong(idStr);
            }
            return initializeFirstId();
        } catch (IOException | NumberFormatException e) {
            System.err.println("加载ID失败: " + e.getMessage());
            return initializeFirstId();
        }
    }

    // 初始化第一个ID
    private Long initializeFirstId() {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;

        String monthStr = month < 10 ? "0" + month : String.valueOf(month);
        String idStr = "86215021" + year + monthStr + "0001";
        Long id = Long.parseLong(idStr);

        saveCurrentId(id + 1);
        return id;
    }

    // 保存当前ID
    private void saveCurrentId(Long id) {
        try (PrintWriter writer = new PrintWriter("id.txt")) {
            writer.println(id);
        } catch (IOException e) {
            System.err.println("保存ID失败: " + e.getMessage());
        }
    }

    // 加载所有账户
    private List<Account> loadAccounts() {
        File file = new File("account.txt");
        if (!file.exists()) {
            return new ArrayList<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            return (List<Account>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("加载账户数据失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    // 保存所有账户
    private void saveAccounts() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("account.txt"))) {
            oos.writeObject(accounts);
        } catch (IOException e) {
            System.err.println("保存账户数据失败: " + e.getMessage());
        }
    }

    @Override
    public Long getId() {
        return currentId;
    }

    @Override
    public void setId(Long id) {
        this.currentId = id;
    }

    @Override
    public Long createId() {
        String idStr = currentId.toString();

        // 解析ID各部分
        int year = Integer.parseInt(idStr.substring(8, 12));
        int month = Integer.parseInt(idStr.substring(12, 14));
        String count = idStr.substring(14);

        // 检查月份变更
        Calendar c = Calendar.getInstance();
        int nowYear = c.get(Calendar.YEAR);
        int nowMonth = c.get(Calendar.MONTH) + 1;

        if (year != nowYear || month != nowMonth) {
            return initializeFirstId();
        }

        // 检查是否达到上限
        if (count.equals("9999")) {
            System.out.println("本月开卡名额已用完，请下个月再来！");
            return -1L;
        }

        // 返回当前ID并更新
        Long newId = currentId;
        currentId++;
        saveCurrentId(currentId);
        return newId;
    }

    @Override
    public boolean insert(Account account) {
        accounts.add(account);
        saveAccounts();
        return true;
    }

    @Override
    public Account selectOne(Long id, String password) {
        for (int i = 0; i < accounts.size(); i++) {
            Account acc = accounts.get(i);
            if (acc != null && acc.getId().equals(id) && acc.getPassword().equals(password)) {
                return acc;
            }
        }
        return null;
    }

    @Override
    public Account selectOne(Long id) {
        for (int i = 0; i < accounts.size(); i++) {
            Account acc = accounts.get(i);
            if (acc != null && acc.getId().equals(id)) {
                return acc;
            }
        }
        return null;
    }

    @Override
    public List<Account> selectAll() {
        return accounts;
    }

    @Override
    public boolean update(Account updatedAccount) {
        for (int i = 0; i < accounts.size(); i++) {
            if (accounts.get(i).getId().equals(updatedAccount.getId())) {
                accounts.set(i, updatedAccount);
                saveAccounts();
                return true;
            }
        }
        return false;
    }
}
